package com.ccom.starter.rabbitmq.core;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: Message 内容对象序列化与反序列化
 *  默认的 SimpleMessageConverter 在发送消息时会将对象序列化成字节数组
 *  若要反序列化对象，需要自定义 MessageConverter
 * @Author: zjj
 * @Date: 2021年12月20日
 */
@Component
public class MapMessageConverter implements MessageConverter {

    @Override
    public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {
        return new Message(object.toString().getBytes(), messageProperties);
    }

    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        String contentType = message.getMessageProperties().getContentType();
        if (null != contentType && contentType.contains("text")) {
            return new String(message.getBody());
        } else {
            ObjectInputStream objInt = null;
            try {
                ByteArrayInputStream byteInt = new ByteArrayInputStream(message.getBody());
                objInt = new ObjectInputStream(byteInt);
                //byte[]转map
                Map map = (HashMap) objInt.readObject();
                return map;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;

    }
}
